package com.fuershiye.woman.monitor.controller;

import com.fuershiye.woman.monitor.beans.Page;
import com.fuershiye.woman.monitor.beans.PageResult;
import com.fuershiye.woman.monitor.beans.Result;
import com.fuershiye.woman.monitor.beans.ViewReportAllValue;
import com.fuershiye.woman.monitor.constants.Massage;
import com.fuershiye.woman.monitor.model.Department;
import com.fuershiye.woman.monitor.model.Indicator;
import com.fuershiye.woman.monitor.service.*;
import com.fuershiye.woman.monitor.utils.DateFormatUtil;
import com.fuershiye.woman.monitor.utils.MyUtilString;
import com.fuershiye.woman.monitor.utils.PageUtil;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

/**
 * 报表数据查询
 *
 * @author yongyongdong
 *
 */
@Controller
@RequestMapping(value = "/report/query")
public class ReportQueryController {

	private static final Logger logger = LoggerFactory
			.getLogger(BulletinController.class);

	@Autowired
	AreaService areaService;
	@Autowired
	DepartmentService departmentService;
	@Autowired
	IndicatorService indicatorService;
	@Autowired
	UserService userService;
	@Autowired
	ReportService reportService;


	/**
	 * 接口文档【1.2、获取当前用户，不同年份上报的数据】
	 * 同部门,多年份,模糊查询

	 * @param iname	【非必传,模糊指标名称查询】
	 * @param years 【必传，用英文逗号隔开的年份  2011,2012,2013】
	 * @return	返回值是value_color
	 *
	 * 适用场景【自己查看自己上报的情况】
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	//	@RequiresPermissions("report:preAlarm")
	@RequestMapping(value = "/self.do")
	@ResponseBody
	public Result self(Long formsid, String iTypes, String iname, String years) {

		if(StringUtils.isBlank(years)||formsid==null||formsid==0) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		List<Integer> yearList = DateFormatUtil.getYearStr2List(years);
		if(yearList.isEmpty()){
			return new Result(Massage.ERROR_YEAR);
		}

		List<Long> iTypesIds = MyUtilString.str2LongByPlaceHolder(iTypes, ",");

		String uname = SecurityUtils.getSubject().getPrincipal() + "";
		Department department = userService.getDepartIdByName(uname);
		if (department == null) {
			logger.error("Error in ReportController user department is null, uname is {}", uname);
			return  new Result(Massage.DEPART_IS_NULL);
		}
		List<Indicator> indicatorList =	indicatorService.listByCondition(iname, formsid, iTypesIds, null, null, 1,null);
		List<Long> indicators = indicatorService.getIndicatorId(indicatorList);
		List<Long> departIds = Lists.newArrayList();
		departIds.add(department.getId());

		List<ViewReportAllValue> reportList = reportService.getReportDate(departIds, formsid, indicators, yearList, 1);
		List<Map<String, Object>> result = reportService.filter(reportList, yearList);

		List<Map<String, Object>> returnresult = Lists.newArrayList();
		for (int i = 0; i < result.size(); i++) {
			Map<String, Object> map = result.get(i);
			for (int j = 0; j < yearList.size(); j++) {
				int year = yearList.get(j);
				if(map.containsKey(year+"")){
					String valueYear = map.get(year+"").toString();
					if(!valueYear.isEmpty()){
//						valueYear = 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
						String[] valueYeararry = valueYear.split("_");
						String rtype = valueYear.split("_",-1)[0];
						String value = valueYear.split("_",-1)[2];
						String remark = valueYear.split("_",-1)[4];
						if(value!=null && value.equals("0.0")){
							map.put(year+"", "0");
						} else {
							//TODO
							map.put(year+"", value);
						}
						map.put("rtype", rtype);
						map.put("remark", remark==null?"":remark);
					}
				}
			}
			returnresult.add(map);
		}

		return new Result(Massage.SUCCESS, new PageResult(result, result.size()));
	}


	/**
	 *  适用场景【查看自己上报的情况】
	 *
	 * @param iname	【非必传,模糊指标名称查询】
	 * @param years 【必传，用英文逗号隔开的年份  2011,2012,2013】
	 * @param page	【非必传】
	 * @param pageSize	【非必传】
	 * com.fuershiye.woman.monitor.model.Indicator
	 *     属性：province 是否是省级监测指标	0:不是(默认);1:是
	 * @return	返回值是value_color
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	//	@RequiresPermissions("report:preAlarm")
	@RequestMapping(value = "/province.do")
	@ResponseBody
	public Result area(Long formsid, String iname, String years, Integer page, Integer pageSize) {

		if(StringUtils.isBlank(years)||formsid==null||formsid==0) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		List<Integer> yearList = DateFormatUtil.getYearStr2List(years);
		if(yearList.isEmpty()){
			return new Result(Massage.ERROR_YEAR);
		}

		String uname = SecurityUtils.getSubject().getPrincipal() + "";
		Department department = userService.getDepartIdByName(uname);
		if (department == null) {
			logger.error("Error in ReportController user department is null, uname is {}", uname);
			return  new Result(Massage.DEPART_IS_NULL);
		}
		List<Long> types = Lists.newArrayList();
		List<Indicator> indicatorList =	indicatorService.listByCondition(iname, formsid, types, 1, 1,null);
		List<Long> indicators = indicatorService.getIndicatorId(indicatorList);
		List<Long> departIds = Lists.newArrayList();
		departIds.add(department.getId());

		List<ViewReportAllValue> reportList = reportService.getReportDate(departIds, formsid, indicators, yearList, 1);
		List<Map<String, Object>> result = reportService.filter(reportList, yearList);

		return new Result(Massage.SUCCESS, new PageResult(result, result.size()));
	}

	/**
	 * 接口文档【1.8、按指标和年份，获取17地市，统计局数据】
	 * 同年份,同指标【17地市统计局部门上报数据】
	 *
	 * @param year	【必传】
	 * @param indicators【必传】
	 * @return
	 *
	 * 适用场景【数据分析 --> 各单位数据分析】
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	// 不需要登录
	// @RequiresPermissions("reportQuery:list")
	@RequestMapping(value = "/sameLevel.do")
	@ResponseBody
	public Result getDepartLevel2AndType7(Integer year, Long formsid, String indicators, Integer page, Integer pageSize) {

		if (!DateFormatUtil.isYear(year) || formsid == null||formsid == 0 || StringUtils.isEmpty(indicators)) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		// 未删除状态数据
		int status = 1;
		// 部门级别 1:国家级;2:省/部级;3:地级市;4:区县级;5:乡镇级;6:其他
		int level2 = 2;
		int level3 = 3;

		// 查找所有的部门
		List<Long> departIds = departmentService.getIdsByCondition(level3, 1);
		if (departIds.isEmpty()) {
			return new Result(Massage.DEPART_IS_NULL);
		}

		// 追加省一级的
		List<Long> departIds2 = departmentService.getIdsByCondition(level2, 1);
		if(departIds2.size()>0){
			departIds.addAll(departIds2);
		}

		List<Long> indicatorsLong = MyUtilString.str2LongByPlaceHolder(indicators, ",");

		// TODO 换了KEY CodeName.DEPART_ID, vral.getDepartid() ; CodeName.CNAME, area.getName()); CodeName.AREA_CODE, area.getCode());
//		List<ViewReportAllValue> reportList = reportService.listInCondition(departIds, formsid, iname, indicators, status, null);
//		List<Area> areaList = areaService.list("", null, null, null, null);
//		if (reportList.isEmpty()) {
//			return new Result(Massage.REPORT_IS_NULL);
//		}
//		List<Map<String, Object>> result = ReportUtil.assemble(indicatorList, reportList, areaList, year, false);

		List<Integer> yearList = Lists.newArrayList();
		yearList.add(year);
		List<ViewReportAllValue> reportList = reportService.getReportDate(departIds, formsid, indicatorsLong, yearList, status);

		Map<String, List<ViewReportAllValue>> resultMap = reportService.filter(reportList);
		List<Map<String, Object>> result = reportService.axis(resultMap, year);

		return new Result(Massage.SUCCESS, new PageResult(PageUtil.getPage(new Page(page, pageSize), result), result.size()));

	}

	/**
	 * 接口文档【1.5、多部门,多指标,包括所有父子关系的指标】
	 * 多部门,多指标,多年份【包括所有父子关系的指标】
	 *
	 * @param years 【必传，用英文逗号隔开的年份  2011,2012,2013】
	 * @param departids	【必传，用英文逗号隔开的年份  11,12,13】
	 * @param indicatorids	【必传，用英文逗号隔开的年份  11,12,13】
	 * @return
	 *
	 * 适用场景【选择多个部门的多个指标，进行比较时】
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	// 不需要登录
	// @RequiresPermissions("reportQuery:list")
	@RequestMapping(value = "/depart/indicator.do")
	@ResponseBody
	public Result getDepartYears(Long formsid, String years, String departids, String indicatorids, Integer page, Integer pageSize) {

		if (formsid==null||formsid==0||StringUtils.isBlank(years) ||
				StringUtils.isBlank(departids)|| StringUtils.isBlank(indicatorids)) {
			return new Result(Massage.ERROR_PARAMETER);
		}

		List<Integer> yearList = DateFormatUtil.getYearStr2List(years);
		if (yearList.isEmpty()) {
			return new Result(Massage.ERROR_YEAR);
		}
		List<Long> departIds = MyUtilString.str2LongByPlaceHolder(departids, ",");
		departIds=MyUtilString.removeValue(departIds, "-1");
		if (departIds.isEmpty()) {
			return new Result(Massage.DEPART_IS_NULL);
		}
		List<Long> indicatoridList = MyUtilString.str2LongByPlaceHolder(indicatorids, ",");
		if(indicatoridList==null){
			return new Result(Massage.INDICATOR_IS_NULL);
		}

		List<Indicator> result = Lists.newArrayList();
		List<Indicator> indicatorList = Lists.newArrayList();

		for (Long indicatorId : indicatoridList) {

			Indicator indicator = indicatorService.get(indicatorId);
			if(indicator==null){
				continue;
			}

			//集合中是否存在该元素
			boolean have =false;
			//如果已经包含该指标了，则跳过
			if(indicatorList!=null && indicatorList.size()>0){
				for (Indicator indicatorCheck : indicatorList) {
					if(indicator.getId().equals(indicatorCheck.getId())){
						have = true;
						break;
					}
				}
			}
			if(have){
				continue;
			}

			Indicator topIndicator = indicator;
			//只有拥有父级指标时，才会查询
			if(indicator.getPid()!=null){
				topIndicator = indicatorService.findParentIndicator(indicator);
			}
			//查询所有子指标,并且保存
			if(topIndicator!=null){
				indicatorList.addAll(indicatorService.getSameBloodByParent(result, topIndicator));
			}
		}
		List<Long> indicatorIds =  indicatorService.getIndicatorId(indicatorList);

		List<ViewReportAllValue> reportList = reportService.getReportDate(departIds, formsid, indicatorIds, yearList, 1);
		List<Map<String, Object>> resultMap = reportService.filter(reportList, yearList, departIds);

		return new Result(Massage.SUCCESS, new PageResult(PageUtil.getPage(new Page(page, pageSize), resultMap), resultMap.size()));

	}

}
